import Vue from 'vue'
import vuex from 'vuex'
import axios from 'axios'

Vue.use(vuex)

export default new vuex.Store({
  state: {
    // 用户信息列表
    user: {
      name: {
        alias: '用户名',
        value: '',
        type: 'string'
      },
      birthday: {
        alias: '生日',
        value: '',
        type: 'date'
      },
      job: {
        alias: '工作',
        value: '',
        type: 'string'
      },
      sex: {
        alias: '性别',
        value: '',
        type: 'radio',
        list: [{
          label: '男',
          value: 1
        },
        {
          label: '女',
          value: 2
        },
        {
          label: '其他',
          value: 3
        }]
      }
    },
    // 用户日报列表
    diaryList: [],
    // 具体工作列表
    workList: {},
    // 用户项目列表
    groupList: {},
    // 用户工作列表
    taskList: {},
    // 登录view类型
    signType: 'signIn',
    // 用户token
    token: '',
    // token: '',
    // 用户权限100为登录
    rule: 10,
    loading: false,
    // 弹出框信息
    itemDialog: {
      itemDialogTitle: '',
      itemDialogName: '',
      isItemDialogOpen: false
    },
    // massageBox信息
    msg: {
      isShow: false,
      showClose: '',
      message: '',
      type: ''
    },
    // 无日报日期列表
    emptyDateList: [],
    // 被编辑日报信息
    diaryFormDate: {
      // 类型
      type: 'today',
      // index
      editIndex: 0,
      // 日报信息
      diaryData: {
        // 日报日期
        work_date: '',
        // 节假日？
        is_holiday: false,
        // 评价
        evaluate: null,
        // 简介
        details: '',
        // 工作信息
        workInfo: [
          {
            // 团队
            group: '',
            // 工作
            task: '',
            // 工作类型
            work_type: '',
            // 时长
            duration: 0
          }
        ]
      }
    }
  },
  mutations: {
    // 刷新页面时保持登录信息
    getCacheData (state) {
      state.token = localStorage.token
      state.rule = 100
      state.user.name.value = localStorage.name
    },
    // 用户登出
    signOut (state) {
      localStorage.clear()
      state.rule = 10
      state.token = ''
      state.user.name.value = ''
    },
    // 用户登录
    signIn (state, user) {
      state.rule = 100
      state.token = user.user_token
      state.user.name.value = user.name
      localStorage.setItem('token', user.user_token)
      localStorage.setItem('name', user.name)
      localStorage.setItem('email', user.email)
    },
    /* 设置用户信息 */
    setuserinfo (state, user) {
      state.user.name.value = user.name
      state.user.birthday.value = user.user_info.birthday
      state.user.job.value = user.user_info.job
      if (user.user_info.sex === 1) {
        state.user.sex.value = '男'
      } else if (user.user_info.sex === 2) {
        state.user.sex.value = '女'
      } else {
        state.user.sex.value = '其他'
      }
      for (let item in state.user.sex.list) {
        if (user.user_info.sex === state.user.sex.list[item].value) {
          state.user.sex.value = state.user.sex.list[item].label
          break
        }
      }
    },
    // message框相关
    openMessage (state, msg) {
      if (state.msg.isShow) {
        state.msg.isShow = false
      } else {
        if (typeof msg === 'object') {
          if (msg.hasOwnProperty('showClose')) {
            state.msg.showClose = msg.showClose
          } else {
            state.msg.showClose = true
          }
          if (msg.hasOwnProperty('type')) {
            state.msg.type = msg.type
          } else {
            state.msg.type = 'error'
          }
          state.msg.message = msg.message
        } else {
          state.msg.showClose = true
          state.msg.type = 'error'
          state.msg.message = msg
        }
        state.msg.isShow = true
      }
    },
    // 改变登录view状态
    changeSignType (state, signType) {
      state.signType = signType
    },
    // 弹窗相关
    isAddItemDialogOpen (state, itemDialogData) {
      if (!itemDialogData) {
        state.itemDialog.isItemDialogOpen = false
      } else {
        state.itemDialog.itemDialogTitle = itemDialogData[0]
        state.itemDialog.itemDialogName = itemDialogData[1]
        state.itemDialog.isItemDialogOpen = true
      }
    },
    /* 将项目、工作信息写入vuex */
    setDiaryData (state, diaryData) {
      let dataArray = []
      let data = diaryData[0]
      for (let i = 0; i < data.length; i++) {
        let item = {id: data[i].id, value: data[i].name}
        dataArray.push(item)
      }
      if (diaryData[1] === 'group') {
        state.groupList = dataArray
      } else {
        state.taskList = dataArray
      }
    },
    /* 将日报信息存入 */
    setDiaryList (state, diaryData) {
      state.diaryList = diaryData.diaryList
      state.workList = diaryData.workList
    },
    /* 设置需要编辑的日报信息 */
    setDiaryFormData (state, data) {
      if (data.type === 'edit') {
        state.diaryFormDate.type = 'edit'
        for (let i = 0; i < state.diaryList.length; i++) {
          if (state.diaryList[i].work_date === data.date) {
            state.diaryFormDate.diaryData.work_date = data.date
            state.diaryFormDate.diaryData.evaluate = state.diaryList[i].evaluate
            state.diaryFormDate.diaryData.details = state.diaryList[i].details
            if (state.diaryList[i].is_holiday === 1) {
              state.diaryFormDate.diaryData.is_holiday = true
            } else {
              state.diaryFormDate.diaryData.is_holiday = false
            }
          }
        }
        let workInfo = []
        let infoList = state.workList[data.date]
        for (let i = 0; i < infoList.length; i++) {
          let info = {}
          info.group = infoList[i].group
          info.task = infoList[i].task
          info.group_id = infoList[i].group_id
          info.task_id = infoList[i].task_id
          info.work_type = infoList[i].work_type
          info.duration = infoList[i].duration
          workInfo.push(info)
        }
        state.diaryFormDate.diaryData.workInfo = workInfo
      } else if (data.type === 'refill') {
        state.diaryFormDate.type = 'refill'
        state.diaryFormDate.diaryData.work_date = data.date
      } else {
        state.diaryFormDate.type = 'add'
        state.diaryFormDate.diaryData = {
          work_date: '',
          evaluate: null,
          details: '',
          is_holiday: false,
          workInfo: [
            {
              group: '',
              task: '',
              work_type: '',
              duration: 0
            }
          ]
        }
        let date = new Date()
        state.diaryFormDate.diaryData.work_date = date.toLocaleDateString()
        state.groupList = []
        state.taskList = []
        return null
      }
    },
    /* 装载未填日报日期 */
    setEmptyDateList (state, emptyDateList) {
      state.emptyDateList = emptyDateList
    }
  },
  actions: {
    /* 注册用 */
    signup ({ commit, state }, userData) {
      axios({
        method: 'post',
        url: 'api/signup',
        data: {
          name: userData.name,
          email: userData.email,
          password: userData.password
        }
      })
      .then((res) => {
        if (res.data.code === '200') {
          commit('openMessage', {
            showClose: false,
            message: '注册成功，5秒钟内跳转',
            type: 'success'
          })
          return true
        } else {
          commit('openMessage', res.data.err)
          return false
        }
      })
      .catch((res) => {
        commit('openMessage', '请求失败，内部错误')
        return false
      })
    },
    /* 登录用 */
    sigin ({ commit, state }, userData) {
      commit('openMessage', {
        showClose: false,
        message: '登录中',
        type: 'info'
      })
      axios({
        method: 'post',
        url: 'api/signin',
        data: {
          email: userData.email,
          password: userData.password
        }
      })
      .then(res => {
        if (res.data.code === '200') {
          commit('signIn', res.data.data)
        } else {
          commit('openMessage', '登录失败请检查信息')
        }
      })
      .catch(res => {
        commit('openMessage', '请求失败，内部错误')
      })
    },
    webRefresh ({ commit, state }) {
      axios({
        method: 'post',
        url: 'api/webrefresh',
        data: {
          user_token: localStorage.token
        }
      })
      .then(res => {
        if (res.data.code === '200') {
          commit('signIn', res.data.data)
        } else {
          commit('signOut', res.data.data)
          commit('openMessage', '登录过期')
        }
      })
      .catch(res => {
        commit('openMessage', '请求失败，内部错误')
      })
    },
    /* 获取用户信息 */
    getUserInfo ({ commit, state }) {
      axios({
        method: 'post',
        url: 'api/getuserinfo',
        data: {
          user_token: state.token
        }
      })
      .then((res) => {
        if (res.data.code === '200') {
          commit('setuserinfo', res.data.data)
        } else {
          commit('openMessage', '请求失败，请重试')
        }
      })
      .catch((res) => {
        commit('openMessage', '内部错误')
      })
    },
    /* 修改用户信息 */
    editUserInfo ({ commit, state }, userInfo) {
      axios({
        method: 'post',
        url: 'api/edituserinfo',
        data: {
          user_token: state.token,
          key: userInfo.key,
          value: userInfo.value
        }
      })
      .then((res) => {
        if (res.data.code === '200') {
          commit('setuserinfo', res.data.data)
        } else {
          commit('openMessage', '修改失败，请重试')
        }
      })
      .catch((res) => {
        commit('openMessage', '内部错误')
      })
    },
    /* 重置密码 */
    resetPassword ({ commit, state }, data) {
      axios({
        method: 'post',
        url: 'api/resetpassword',
        data: {
          user_token: state.token,
          old_password: data.oldPassword,
          new_password: data.newPassword
        }
      })
      .then((res) => {
        if (res.data.code === '200') {
          commit('openMessage', {message: res.data.data, type: 'success'})
          commit('signOut')
        } else {
          commit('openMessage', '内部错误')
        }
      })
      .catch((res) => {
        commit('openMessage', '请求失败，请重试')
      })
    },
    /* 获得未填日报日期列表 */
    getEmptyDateList ({ commit, state }, selsectTime) {
      axios({
        method: 'post',
        url: 'api/getemptydatelist',
        data: {
          user_token: state.token,
          selsectTime: selsectTime
        }
      })
      .then((res) => {
        if (res.data.code === '200') {
          commit('setEmptyDateList', res.data.data)
        } else {
          commit('openMessage', '获取失败')
        }
      })
      .catch((res) => {
        commit('openMessage', '内部错误')
      })
    },
    /* 获得日报列表 */
    getDiaryList ({ commit, state }, selsectTime) {
      state.loading = true
      axios({
        method: 'post',
        url: 'api/getdiarylist',
        data: {
          user_token: state.token,
          selsectTime: selsectTime
        }
      })
      .then((res) => {
        if (res.data.code === '200') {
          commit('setDiaryList', res.data.data)
        } else {
          commit('openMessage', '数据获取失败')
        }
        state.loading = false
      })
      .catch((res) => {
        commit('openMessage', '内部错误')
        state.loading = false
      })
    },
    /* 提交日报信息 */
    postDiary ({ commit, state }, diaryEditForm) {
      axios({
        method: 'post',
        url: 'api/adddiary',
        data: {
          user_token: state.token,
          type: state.diaryFormDate.type,
          diary_data: diaryEditForm
        }
      })
      .then((res) => {
        if (res.data.code === '200') {
          commit('setDiaryFormData', 'today')
        } else {
          commit('openMessage', '未知错误')
        }
      })
      .catch((res) => {
        commit('openMessage', '请求失败，内部错误')
      })
    },
    /* 获取项目、工作列表 */
    getDiaryDataList ({ commit, state }, dataName) {
      axios({
        method: 'post',
        url: 'api/get' + dataName + 'list',
        data: {
          user_token: state.token
        }
      })
      .then((res) => {
        if (res.data.code === '200') {
          commit('setDiaryData', [res.data.data, dataName])
        } else {
          commit('openMessage', '信息获取失败')
        }
      })
      .catch((res) => {
        commit('openMessage', '请求失败，内部错误')
      })
    },
    /* 提交新的项目、工作信息 */
    postDiaryData ({ commit, state }, postData) {
      axios({
        method: 'post',
        url: 'api/add' + state.itemDialog.itemDialogName,
        data: {
          user_token: state.token,
          data: postData
        }
      })
      .then((res) => {
        if (res.data.code === '200') {
          commit('openMessage', {message: res.data.data, type: 'success'})
        } else if (res.data.code === '400') {
          commit('openMessage', '项目已存在')
        }
      })
      .catch((res) => {
        commit('openMessage', '请求失败，内部错误')
      })
    }
  }
})
